dojo.provide("dojot.util.EditInPlaceField");
dojo.require("dojot._base");
dojo.requireLocalization("dojot", "common");
dojo.requireLocalization("dojot", "picDescEditInPlaceArea");

/**
 * 可编辑区域主类
 */
dojo.declare("dojot.util.EditInPlaceField",null,{
	 //是否有值
	isHaveValue: false,
	
	 //如果没有值得话显示默认的文字
	defaultValue: "",
	
	//保存按钮默认文字
	buttonOk:"",

	buttonCancel:"",
	
	//输入区域默认输入的最大字数
	maxLength:200,
	
	//默认每行能输入的最大字数
	maxLineLength:20,
	
	//超过长度提示错误信息
	overLengthErrorInfo:"",
	
	//文本输入区域默认长度
	textFieldWith:"480px",
	
	//默认是否允许可以编辑
	allowChangeValue:true,
	
	//是否显示全部的静态内容,
	showAll:false,
	
	//当前内容
	value:"",
	
	//用户当前输入的文字长度
	currertContentLength:0,
	//用户最大可以输入的文字长度
	maxContentLength:200,
	
	//用户输入文字提示信息template
	contentLengthSuggestTemplate: "${currertContentLength}/${maxContentLength}",
	//默认显示静态内容的文字长度
	defaultShowLetterLength:10,
	constructor: function(obj){	
		//默认的一些主要参数设置
		dojo.mixin(this,obj);
		//模板方法,交给子类有机会初始化一些信息
		this._init();
		this.createElements(this.id);
	},
	_init:function(){
		//国际化信息
		this._messages = dojo.i18n.getLocalization("dojot", "common", dojo.locale);
		dojo.forEach(["buttonOk","buttonCancel"], function(prop){
			if(!this[prop]){ this[prop] = this._messages[prop]; }
		}, this);
	},
	//创建基本元素,模板方法，具体的创建由子类完成
	createElements: function(id) {
		this._createContainerElement();
		this._createStaticElement();
		this._createFieldElement();
		this._createButtonElement();
		this._createLengthSuggestElement();
		this._convertToText();
		this._attachEvents();
		//当输入长度超过,进行处理
		dojo.subscribe("overLength",dojo.hitch(this,"_dealWithOverLength"));	
	},
	_createContainerElement:function(){
		throw new Error('dojot.util.EditInPlaceField Unimplemented Memthod _createContainerElement subclass responsibility');
	},
	_createStaticElement:function(){
		throw new Error('dojot.util.EditInPlaceField Unimplemented Memthod _createStaticElement subclass responsibility');
	},
	_createFieldElement:function(){
		throw new Error('dojot.util.EditInPlaceField Unimplemented Memthod _createFieldElement subclass responsibility');
	},
	_createLengthSuggestElement:function(){
		this.lengthSuggestElement = this._createElement("span","",this.containerElement);
	},
	_createButtonElement:function(){
		this.bottonElement = this._createElement("div",null,this.containerElement);
		this.saveButton = this._createInput("button",this.buttonOk,this.bottonElement);
		this.cancelButton = this._createInput("button",this.buttonCancel,this.bottonElement);
	},
	_convertToText: function(){
		throw new Error('dojot.util.EditInPlaceField Unimplemented Memthod _convertToText subclass responsibility');
	},
	_checkValueLength: function(){
		throw new Error('dojot.util.EditInPlaceField Unimplemented Memthod _checkValueLength subclass responsibility');
	},
	_save: function(){
		throw new Error('dojot.util.EditInPlaceField Unimplemented Memthod _save subclass responsibility');
	},
	_cancel: function(){
		this._convertToText();
	},
	_saveToServer:function(newValue){
		//defalut no save to server
	},
	_attachEvents: function(){
		var that = this;
		dojo.connect(this.staticElement,"onclick",that,"_convertToEditable");
		dojo.connect(this.saveButton,"onclick",that,"_save");
		dojo.connect(this.cancelButton,"onclick",that,"_cancel");
		dojo.connect(this.fieldElement, "onkeyup", that,"_checkValueLength");
		//dojo.connect(this.fieldElement, "onchange", that,"_checkValueLength");
	},
	//一些辅助方法
	_createInput: function(type,labelValue,parentElement){
		var input = dojo.doc.createElement('input');
		input.type = type;
		input.value = labelValue;
		parentElement.appendChild(input);
		return input;
	},
	_createElement: function(type,value,parentElement){
		var element = dojo.doc.createElement(type);
		element.innerHTML = value || "";
		parentElement.appendChild(element);
		return element;
	},
	getValue:function(){
		return this.value;
	},
	setValue:function(value){
		value = value.deentityify();
		this.value = value;
		this._setFieldValue(value);
		this._setStaticValue(value);
		this._setLengthSuggestElement(value);
	},
	_setFieldValue:function(){
		throw new Error('dojot.util.EditInPlaceField Unimplemented Memthod _setFiledValue subclass responsibility');
	},
	_setStaticValue:function(){
		throw new Error('dojot.util.EditInPlaceField Unimplemented Memthod _setStaticValue subclass responsibility');
	},
	_dealWithOverLength: function(data){
		console.log("_dealWithOverLength-->"+this.overLengthErrorInfo);
		if(!dojo.attr(this.saveButton,"disabled")){
			dojo.attr(this.saveButton,{
				disabled:true
			});
		}
	},
	_cancelDealWithOverLength: function(){
		if(dojo.attr(this.saveButton,"disabled")){
				dojo.attr(this.saveButton,{
				disabled:false,
				value:this.buttonOk
			});
		}	
	},
	_setLengthSuggestElement:function(value){
		var obj = {
			currertContentLength:value.length,
			maxContentLength:this.maxContentLength
		}
		this.lengthSuggestElement.innerHTML = dojo.string.substitute(this.contentLengthSuggestTemplate,obj);
	},
	_checkValueLength: function(e){
		var value = this.fieldElement.value;	
		this._setLengthSuggestElement(value);
		if(value && value.length > this.maxLength){
			dojo.publish("overLength");
		}else{
			this._cancelDealWithOverLength();
		}
	},
	setAllowChangeValue: function(allowChangeValue){
		this.allowChangeValue = allowChangeValue;
	}
});

dojo.declare("dojot.util.EditInPlaceFieldInput",dojot.util.EditInPlaceField,{

	_createContainerElement:function(){
		this.containerElement = this._createElement("span",null,this.parentElement);
	},
	_createStaticElement:function(){
		this.staticElement = this._createElement("span",this.value,this.containerElement);
	},
	_createFieldElement:function(){
		this.fieldElement = this._createInput("text",this.value,this.containerElement);
	},
	_convertToText: function(){
		dojo.style(this.staticElement, "display","inline");
		dojo.style(this.fieldElement, "display","none");
		dojo.style(this.bottonElement, "display","none");
		dojo.style(this.lengthSuggestElement, "display","none");
	},
	_convertToEditable: function() {	
		dojo.style(this.staticElement, "display","none");
		dojo.style(this.fieldElement, "display","inline");
		dojo.style(this.bottonElement, "display","inline");
		dojo.style(this.lengthSuggestElement, "display","inline");
	},
	_save: function(dealWith) {
		var newValue = dojo.string.trim(this.getValue());
		if(newValue !== this.getValue()){
			this._saveToServer(newValue);
		}else{
			this._convertToText();	
		}
	},
	_setFieldValue:function(value){
		dojo.attr(this.fieldElement,"value", value); 
	},
	_setStaticValue:function(value){	
		this.staticElement.innerHTML = value; 
	}
});

dojo.declare("dojot.util.EditInPlaceArea",dojot.util.EditInPlaceField,{
	
	_createContainerElement:function(){
		this.containerElement = this._createElement("div",null,this.parentElement);
	},
	_createStaticElement:function(){
		this.staticElement = this._createElement("p",this.value,this.containerElement);
	},
	_createFieldElement:function(){		
		this.fieldElement = document.createElement('textarea');
		this.fieldElement.value = this.value;
		this.containerElement.appendChild(this.fieldElement);
	},
	_convertToEditable: function() {
		if(!this.allowChangeValue){
			return;
		}
		this.staticElement.style.display = 'none';
		this.fieldElement.style.display = 'block';
		this.bottonElement.style.display = 'block';
		this.lengthSuggestElement.style.display = 'block';
	},
	_convertToText: function() {
		this.staticElement.style.display = 'block';
		this.fieldElement.style.display = 'none';
		this.bottonElement.style.display = 'none';
		this.lengthSuggestElement.style.display = 'none';
	},
	_save: function(dealWith) {
		//首先需要拿出新的值,然后和当前对象的value进行比较如果不同则保存到server
		//如果相同则直接转换就行。
		var newValue = dojo.string.trim(this.fieldElement.value);
		//newValue = newValue.replace(/\n/g,"<br/>");
		if(newValue !== this.value){
			this._saveToServer(newValue);
		}else{
			this._convertToText();	
		}
	},
	_setFieldValue:function(value){
		this.fieldElement.innerHTML = ""; // wipe out old nodes
		var fieldValue = value.replace(/<br\/>/g,"\n");
		this.fieldElement.value = fieldValue;
	},
	//设置静态需要把\n给替换成BR
	_setStaticValue:function(value){	
		//如果描述不为空
	console.log("showAll----->"+this.showAll);
		if(value && dojo.string.trim(value).length > 0){
			if(this.showAll){
				var staticValue = value.replace(/\n/g," ");
				//显示全部,如果大于默认行长度添加换行
				var tempArray = staticValue.split("");
				var maxLetterLength = staticValue.length;
				var loopCount = maxLetterLength / this.maxLineLength;
				console.log("1-->"+maxLetterLength+"-"+this.maxLineLength+"-"+loopCount);
				var loopCount = (maxLetterLength % this.maxLineLength == 0) ? loopCount : Math.ceil(loopCount);
				for(var i=1; i < loopCount;i++){
					tempArray.splice(i*this.maxLineLength+1,0,"{br}");
				}
				this.staticElement.innerHTML = tempArray.join("").entityify().replace(/\{br\}/g,"<br/>");
			}else{
				//如果多行只显示第一行,如果第一行超过默认行长度，则截取.
				var multiLine = value.split("\n");
				var firstLine = multiLine[0]; 
				console.log("firstLine--------------------------->"+firstLine);
				if(firstLine.length > this.maxLineLength){
					firstLine = firstLine.substring(0,this.maxLineLength)+"...";
				}
				this.staticElement.innerHTML = firstLine.entityify();
			}
		}else{
			console.log("------------defaultValue--------------");
			if(this.allowChangeValue){
				this.staticElement.innerHTML = this.defaultValue;
			}else{
				this.staticElement.innerHTML = "";
			}
		}
	}
});
//和相册相关的一个子类

dojo.declare("dojot.util.PicDescEditInPlaceArea",dojot.util.EditInPlaceArea,{
	//图片id
	picId:"",
	
	//图片描述保存地址
	descSaveUrl:"",
	
	constructor:function(){
		this._messages = dojo.mixin(this._messages,dojo.i18n.getLocalization("dojot", "picDescEditInPlaceArea", dojo.locale));		
		var picId = dojo.attr(this.parentElement,"picid");	
		if(picId){
			this.picId = picId;	
		}
		//获取子资源的ownerId,主要用于判断子资源的权限
		if(dojot.security){
			var ownerId = dojo.attr(this.parentElement,"ownerid");
			if(ownerId){
				if(!dojot.security.isHaveAccess(["owner","admin"],ownerId)){
					this.setAllowChangeValue(false);
				}
			}
		}	
	},
	_init:function(){
		//国际化信息
		this.inherited(arguments);
		this._messages = dojo.mixin(this._messages,dojo.i18n.getLocalization("dojot", "picDescEditInPlaceArea", dojo.locale));
		//要覆盖一些默认值
		dojo.forEach(["buttonOk","defaultValue"], function(prop){
				this[prop] = this._messages[prop]; 
		}, this);
	},
	_createContainerElement:function(){

		this.inherited(arguments);
		dojo.style(this.containerElement,{
			"position": "relative",
			"zIndex":77,
			"border":"0px solid red",
			"width":this.textFieldWith,
			"height":"20px",
			"float":"left"
		});
	},
	_createStaticElement:function(){
		this.inherited(arguments);
		dojo.style(this.staticElement,{
			"width":this.textFieldWith,
			"marginTop":"0px",
			"marginLeft":"0px"
		});
	},
	_createFieldElement:function(){
		this.inherited(arguments);
		dojo.style(this.fieldElement,{
			width:this.textFieldWith,
			height:"50px",
			"marginTop":"2px",
			"marginLeft":"0px",
			"position": "absolute",
			"bottom":"-35px",
			"left":"2px",
			"zIndex":77,
			"background":"#F5F6BE none repeat scroll 0 0"
		});
	},
	_createButtonElement:function(){
		this.inherited(arguments);
		dojo.style(this.bottonElement,{
			width:parseInt(this.textFieldWith)+20+"px",
			"height":"20px",
			"marginTop":"2px",
			"position": "absolute",
			"left":"15px",
			"bottom":"-60px",
			"zIndex":99
		});
		
	},
	_createLengthSuggestElement:function(){
		this.inherited(arguments);
		dojo.style(this.lengthSuggestElement,{
			"height":"20px",
			"marginTop":"2px",
			"position": "absolute",
			"left":"0px",
			"bottom":"-60px",
			"zIndex":200
		});
		
	},
	setPicId:function(picId){
		this.picId = picId;
	},
	getPicId: function(){
		return this.picId;
	},
	setSaveUrl: function(url){
		this.descSaveUrl = url;
	},
	_saveToServer:function(newValue){
		var that = this;
		dojo.xhrPost({
			url: that.descSaveUrl,
			content: { 
				method: "editDesc",
				picId:that.getPicId(),
				desc:newValue
			},
			load:function(data){
				that.value = newValue;
				that.setValue(newValue);
				that._convertToText();	
			},
			error:function(error){
				console.log(error);
				console.log('Error saving value.'); 
			},
			handleAs: "json"
		});
	}
});
